package cn.com.fattiger.framework.semaphore;

import java.util.concurrent.Semaphore;

/**
 * 
 * @author fattiger.xiaoyang
 * @date 2016/04/05
 */
public class SemaphoreDemo {

	public static void main(String[] args) {
		final int COUNT_NUM = 10;
		Semaphore semaphore = new Semaphore(5);
		for(int i= 0; i < COUNT_NUM; i++){
			new Thread(new CountHandler(semaphore, i)).start();
		}
	}

}
class CountHandler implements Runnable{
	private Semaphore semaphore;
	private int i;
	public CountHandler(Semaphore semaphore,int i){
		this.semaphore = semaphore;
		this.i = i;
	}
	
	@Override
	public void run() {
		try {
			semaphore.acquire();
	        System.out.println("工人" + this.i + "占用一个机器在生产...");
	        Thread.sleep(2000);
	        System.out.println("工人" + this.i + "释放出机器");
	        semaphore.release();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}